<template>
  <wd-form
    custom-class="custom-form"
    ref="formRef"
    :model="form"
    :rules="rules"
  >
    <wd-cell-group border>
      <template v-for="item of formList" :key="item.prop">
        <wd-picker
          v-if="item.type === 'changePicker'"
          v-model="form[item.prop]"
          :label="item.label"
          :columns="item.columns"
          :clearable="item.clearable !== false"
          :column-change="item.columnChange"
          :display-format="item.displayFormat || displayFormat"
        ></wd-picker>
        <slot
          v-else-if="item.type === 'firstSlot'"
          name="firstFormItemSlot"
          :item="item"
        ></slot>

        <!-- 需要一个默认值数字 -->
        <wd-cell
          v-else-if="item.type === 'rate'"
          :prop="item.prop"
          :title="item.label"
          :title-width="item.labelWidth + 'px' || '80px'"
        >
          <wd-rate
            v-model="form[item.prop]"
            :active-color="
              item.activeColor || [
                'linear-gradient(180deg, rgba(255,238,0,1) 0%,rgba(250,176,21,1) 100%)',
                'linear-gradient(315deg, rgba(245,34,34,1) 0%,rgba(255,117,102,1) 100%)',
              ]
            "
          />
        </wd-cell>
        <wd-input
          v-else
          v-model="form[item.prop]"
          :label="item.label"
          :label-width="item.labelWidth + 'px' || '80px'"
          :prop="item.prop"
          :placeholder="item.placeholder || '请输入' + item.label"
        />
      </template>
    </wd-cell-group>

    <view class="footer pb-24" v-if="customFooterFlag">
      <slot name="footer"></slot>
    </view>
    <view class="footer flex pb-24" v-else>
      <wd-button type="info" @click="reset">重置</wd-button>
      <wd-button type="primary" @click="commit">提交</wd-button>
    </view>
  </wd-form>
</template>

<script setup>
import { ref } from "vue";

const props = defineProps({
  rules: {
    type: Object,
  },
  form: {
    type: Object,
    required: true,
    default: () => ({}),
  },
  formList: {
    type: Object,
    required: true,
    default: () => [],
  },
  customFooterFlag: Boolean,
});

const emits = defineEmits(["commit"]);

function displayFormat(items) {
  return items.map((item) => item.label).join("-");
}

const formRef = ref(null);
const reset = () => {
  for (const k in props.form) {
    props.form[k] = "";
  }
};
const commit = () => {
  formRef.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        emits("commit");
      }
    })
    .catch((err) => console.log(err));
};
</script>

<style scoped lang="scss"></style>
